package com.example.weatherapp;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.weatherapp.adapter.CityManageAdapter;
import com.example.weatherapp.beans.PlaceBean;
import com.example.weatherapp.beans.WeatherRealtime;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class ManageActivity extends AppCompatActivity {

    private RecyclerView rvCityManage;
    private CityManageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage);
        rvCityManage = findViewById(R.id.rvCities);
        findViewById(R.id.ivBack).setOnClickListener(v -> finish());
        findViewById(R.id.llSearch).setOnClickListener(v -> startActivity(new Intent(ManageActivity.this, SearchActivity.class)));
        findViewById(R.id.edtSearch).setOnClickListener(v -> startActivity(new Intent(ManageActivity.this, SearchActivity.class)));
        LinearLayoutManager layoutManager = new LinearLayoutManager(ManageActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvCityManage.setLayoutManager(layoutManager);
    }

    private void renderData() {
        SharedPreferences preferences = getSharedPreferences("cities", MODE_PRIVATE);
        String cityList = preferences.getString("cityList", "[]");
        Gson gson = new Gson();
        Type listType = new TypeToken<List<PlaceBean>>() {
        }.getType();
        List<PlaceBean> placeBeans = gson.fromJson(cityList, listType);
        for (PlaceBean placeBean : placeBeans) {
            getWeatherRealtime(placeBean);
        }
        adapter = new CityManageAdapter(placeBeans) {
            @Override
            public void selectCity(PlaceBean city) {
                Intent intent = new Intent(ManageActivity.this, WeatherResultActivity.class);
                intent.putExtra("city", city.getName());
                intent.putExtra("lng", city.getLng());
                intent.putExtra("lat", city.getLat());
                startActivity(intent);
            }

            @Override
            public void deleteCity(PlaceBean city) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ManageActivity.this);
                builder.setTitle("提示");
                builder.setMessage("确定要删除" + city.getName() + "吗？");
                builder.setPositiveButton("确定", (dialog, which) -> {
                    placeBeans.remove(city);
                    preferences.edit().putString("cityList", gson.toJson(placeBeans)).commit();
                    adapter.notifyDataSetChanged();
                });
                builder.setNegativeButton("取消", null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        };
        rvCityManage.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        renderData();
    }

    /**
     * 获取城市实时天气数据
     *
     * @param placeBean
     */
    private void getWeatherRealtime(PlaceBean placeBean) {
        try {
            OkHttpClient client = new OkHttpClient();
            String url = "https://api.caiyunapp.com/v2.5/VCdxijtyAdrjqrCd/" + placeBean.getLng() + "," + placeBean.getLat() + "/realtime.json";
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String repContent = response.body().string();
                        Gson gson = new Gson();
                        WeatherRealtime weatherRealtime = gson.fromJson(repContent, WeatherRealtime.class);
                        placeBean.setTemp((int) weatherRealtime.getResult().getRealtime().getTemperature() + "°C");
                        runOnUiThread(() -> adapter.notifyDataSetChanged());
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}